from django.shortcuts import render

# Create your views here.

# 访问格式http://localhost:8000/goods/category/1
from django.views import View
from rest_framework.views import APIView

from apps.goods.models import Goods
from apps.goods.serializers import GoodsSerializers
from utils import ResponseMessage
from django.http import JsonResponse
import json


class GoodsCategoryAPIView(APIView):
    """
    获取指定类别商品的分页数据

    参数:
    - request: 请求对象，包含请求相关信息
    - category_id: 商品类别ID，用于筛选商品数据
    - page: 页码，用于指定当前请求的数据页

    返回:
    - 成功时返回包含商品数据的ResponseMessage对象
    """
    def get(self, request, category_id, page):
        # 计算当前页码的起始索引
        current_page = (page - 1) * 20
        # 计算当前页码的结束索
        end_data = page * 20
        # 根据类别ID筛选商品数据，并获取指定范围的商品信息
        category_data = Goods.objects.filter(type_id=category_id).all()[current_page:end_data]

        result_list = []

        for m in category_data:
            # 将每个商品对象转换为字符串表示并添加到结果列表
            result_list.append(m.__str__())
        # 返回成功消息，包含商品数据列表
        return ResponseMessage.GoodsResponseMessage.success(result_list)


class GoodsDetailAPIView(APIView):
    def get(self, request, sku_id):
        """
        获取指定SKU编号的商品详情
        """
        goods_data = Goods.objects.filter(sku_id=sku_id).first()
        result = GoodsSerializers(instance=goods_data)

        return ResponseMessage.GoodsResponseMessage.success(result.data)